package com.skywaregroup.arenal;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ValidPIDLogicValidator implements
		ConstraintValidator<ValidPIDLogic, Card> {

	@Override
	public void initialize(ValidPIDLogic constraintAnnotation) {
	}

	@Override
	public boolean isValid(Card card, ConstraintValidatorContext context) {
		if (card == null) {
			return true;
		}
		
		if ((card.pidType == null) ^ (card.countryCode == null)) {
			if (card.pidType == null) {
				//EU citizen
				return (card.pid != null && card.pid.matches(BgPID.EU_CITIZEN_PATTERN));
			} else {
				//BG citizen
				switch (card.pidType) {
				case 1:
					//EGN
					BgPID egn = new BgPID(true, card.pid);
					return egn.getIsValid();
				case 2:
					//ENCh
					BgPID ench = new BgPID(false, card.pid);
					return ench.getIsValid();
				case 3: case 4:
					//Refugee or special statute, no formal check, just length
					return (card.pid != null && card.pid.matches(BgPID.SPECIAL_NUM_PATTERN));
				default:
					//Any other - invalid
					return false;
				}
			}
		} else {
			//Either pidType or countryCode must be non-null, but not both
			return false;
		}

	}
}
